<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="100%" @ok="handleSubmit">

    <div>
      <Descriptions size="small" title="试卷信息"
                    style="margin-top: 10px;" v-if="dataList.publishPaperId">
        <DescriptionsItem label="预计考试时间">
          {{dataList.startTime}}
        </DescriptionsItem>
        <DescriptionsItem label="试卷规则类型">
          {{dataList?.exPaper.ruleType==1?'团队试卷':'面试试卷'}}
        </DescriptionsItem>
        <DescriptionsItem label="考试状态">
          {{getStatusName()}}
        </DescriptionsItem>
        <DescriptionsItem label="考试模式">
          {{dataList?.exPaper.model==1?'单一模块':'整张试卷'}}
        </DescriptionsItem>
        <DescriptionsItem label="考试分钟数">
          {{dataList?.exPaper.limitTime}}分钟
        </DescriptionsItem>
        <DescriptionsItem label="切换到下一分类" v-if="dataList?.exPaper.ruleType==1">
          <span v-if="dataList?.status==2" style="color: red">考试已结束</span>
          <Button v-else type="primary" @click="startFn" :loading="loading" >开始/下一个</Button>
        </DescriptionsItem>
<!--        v-if="dataList?.exPaper.ruleType==1"-->
        <DescriptionsItem label="重置" >
          <Button   @click="testFn" :loading="loading" >重置</Button>
        </DescriptionsItem>
        <DescriptionsItem label="个人排名" v-if="dataList?.exPaper.ruleType==1">
          <Button type="primary"  @click="rangkFn"  >查看个人排名</Button>
        </DescriptionsItem>
        <DescriptionsItem label="团队排名" v-if="dataList?.exPaper.ruleType==1">
          <Button type="primary"  @click="teamRangkFn"  >查看团队排名</Button>
        </DescriptionsItem>
        <DescriptionsItem label="交卷" v-if="dataList?.exPaper.ruleType==1">
          <Button  type="primary" @click="sysNotifySubmitFn" :loading="loading" >交卷</Button>
        </DescriptionsItem>
      </Descriptions>

      <div style="background: white;">

        <div style="border-top: 1px solid #e8eaec;display: flex;">
          <div v-for="(item, index) in titleGroupColumnsRef" class="foot_item "  :style="getHeadStyle(item)" :key="index">
            <div class="foot_item_row" >
              {{item.title}}
            </div>
          </div>
        </div>
        <div  v-if="groupList.length > 0">
          <div v-for="(item2, index2) in groupList"  style="display: flex" :key="index2" >
            <div v-for="(item, index) in titleGroupColumnsRef" class=" foot_item "  :style="getHeadStyle(item)" :key="index">
              <div v-if="item2[item.field]!=null" class="foot_item_row">
                  <div v-if="item.formatter!=null" :style="{color:item2.color}">
                    {{item.formatter({cellValue:item2[item.field],row:item2})}}
                  </div>
                <div v-else-if="item.editRender&&item.editRender.name">
                   <vxe-number-input v-if="item.editRender.name=='VxeNumberInput'"  v-model="item2[item.field]" placeholder="请输入" size="mini" style="width: 100%" :disabled="!item2.isEdit"></vxe-number-input>
                   <vxe-input v-if="item.editRender.name=='VxeInput'"  v-model="item2[item.field]" placeholder="请输入" size="mini" style="width: 100%" :disabled="!item2.isEdit"></vxe-input>
                </div>
                <div v-else>{{item2[item.field]}}</div>
              </div>
              <div v-if="item.title=='操作'" class="foot_item_row">
                <TableAction outside :actions="getActions(item2,index2)" />
              </div>
            </div>

          </div>
          <div class="foot_item">
            <span style="padding-left: 10px"> 共: {{groupList.length}}条</span>
          </div>
        </div>
        <Empty v-if="groupList.length == 0"></Empty>
         <div>
           <div>
             <Button type="primary" @click="getScoketUsersFn" size="small" style="margin-top: 3px">刷新在线人数</Button>
             <span v-if="userNames.length">{{userNames.length}}人</span>

           </div>

           <div v-for=" (item,index) in userNames" style="padding-top: 3px">
              {{item}}
           </div>
         </div>
      </div>
    </div>

    <ChooseQuestionDrawer @register="choose[0]" @success="handleSuccess"></ChooseQuestionDrawer>
    <UserRankDrawer @register="rank[0]" @success="handleSuccess"></UserRankDrawer>
    <TeamRankDrawer @register="team[0]" @success="handleSuccess"></TeamRankDrawer>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, reactive, watchEffect } from 'vue';
import {Button, Empty, Descriptions, DescriptionsItem, MonthPicker} from 'ant-design-vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useDrawer } from '@/components/Drawer';
// import { useWebSocket } from '@vueuse/core';
import {
  formSchema,
  titleGroupColumns
} from './role.data';

import { BasicModal, useModalInner } from '@/components/Modal';
import ChooseQuestionDrawer from './ChoosePaperQuestionDrawer.vue';
import UserRankDrawer from './UserRankDrawer.vue';
import TeamRankDrawer from './TeamRankDrawer.vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {getPublishPaper, startPublishPaper, testTaskScheduler,sysNotifySubmit,getScoketUsers,againPublishGroup,savePublishGroup} from '@/api/heng/ex';
import { useMessage } from "@/hooks/web/useMessage";
const choose = useDrawer();
const rank = useDrawer();
const team = useDrawer();
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();


const id = ref("")


const loading = ref(false);
// const tableRef = ref();

const dataList = ref({});
const groupList=ref([]);//{categoryName:"测试",type:1}

const titleGroupColumnsRef = ref(titleGroupColumns);


const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data.isUpdate;

  id.value = "";
  groupList.value=[];
  id.value = data.record.publishPaperId;
  paperDetailFn();
  getScoketUsersFn();

});

const getTitle = computed(() => ('试卷信息保存'));


function paperDetailFn(){
  setDrawerProps({ confirmLoading: true });

  getPublishPaper({publishPaperId:id.value}).then((res) => {
    if(res.code==200){
      let json=res.data;
      dataList.value = json;
      groupList.value= json.groups;

    }else{
      createMessage.error(res.message);
    }
  }).finally(e=>{
    setDrawerProps({ confirmLoading: false });

  })


}
const userNames=ref([])

function getScoketUsersFn(){
  loading.value = true;
  getScoketUsers({publishPaperId:id.value}).then((res) => {
    if(res.code==200){
      userNames.value=res.data;
      paperDetailFn();

    }else{
      createMessage.error(res.message);
    }
  }).finally(e=>{
    loading.value = false;
    setDrawerProps({ confirmLoading: false });

  })
}

function getStatusName(){
  let val = '';
  switch (dataList.value?.status) {
    case 0:
      val = '未开始';
      break;
    case 1:
      // color='orange';
      val = '进行中';
      break;
    case 2:
      val = '已结束';
      break;
  }
  return val;
}

async function handleSubmit() {
  try {

    // values.publishPaperId = id.value;
    // let t_list = groupList.value;
    // if (t_list.length == 0) {
    //   createMessage.error("请选择题目:添加题目分类>选题!");
    //   return;
    // }
    // values.groups = t_list;
    // paperSave(values).then(res => {
    //   sunccFn(res)
    // });


  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}

function sunccFn(result) {
  if (result && result.code == 200) {
    createMessage.success(result.message);
  } else {
    createMessage.error(result.message);
  }
  closeDrawer()
  emit('success');
}

function cancelFn() {
  //  tableRef.value.clearValidate();
}

function rangkFn(){
  rank[1].openDrawer(true, {publishPaperId:id.value})
}

function teamRangkFn(){
  team[1].openDrawer(true, {publishPaperId:id.value})
}

function getHeadStyle(head){
  let style = {};
  if(head.width){
    style.width=head.width+'px';
  }else{
    style.flex=1;
  }
  return style;
}

function getActions(record,index) {
  let obj1={
    // icon: 'clarity:note-edit-line',
    label: '查看题目',
    onClick: handleEdit.bind(null, record,index),
  };
  let obj2={
      label: '修改',
      loading: record.loading,
     onClick: openEditFn.bind(null, record,index),
    };
  let obj3={
    label: '保存',
    color:"success",
    onClick: saveEditFn.bind(null, record,index),
  };
  let obj4={
    label: '重考',
    color:"error",
    loading: record.loading,
    popConfirm: {
      title: '是否确认单独重考该模块?',
      placement: 'left',
      confirm: againFn.bind(null, record),
    },
   // onClick: saveEditFn.bind(null, record,index),
  };
  let arr = [];
   if(record.isEdit){
     arr = [obj1,obj3,obj4];
   }else{
     arr = [obj1,obj2,obj4];
   }

  return arr;
}





function handleSuccess(item) {

  if(item.isUpdate) {
    groupList.value[item.index]=item;
  }else{
    groupList.value.push(item);
  }
}

function handleEdit(record: Recordable,index) {
  record.isUpdate=true
  record.index = index;
  choose[1].openDrawer(true, record)
}

//开启修改
function openEditFn(record: Recordable,index) {
  record.isEdit=true
  record.index = index;
}
//保存修改
function saveEditFn(record: Recordable,index) {
  record.isEdit=false
  record.index = index;
  record.loading=true;
  savePublishGroup(record).then(res=>{
    if(res.code==200){
      createMessage.success(res.message);
      paperDetailFn();

    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    record.loading=false;

  })
}

//重考
function againFn(record: Recordable,index){
  record.isEdit=false;
  record.loading=true;

  againPublishGroup(record).then(res=>{
    if(res.code==200){
      createMessage.success(res.message);
      paperDetailFn();

    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    record.loading=false;
  })
}

function startFn(){
  loading.value = true;
  startPublishPaper({publishPaperId : id.value}).then((res) => {
    if(res.code==200){
      paperDetailFn();
    }
  }).finally(e=>{
    loading.value = false;
  })
}

function testFn(){
  loading.value = true;
  testTaskScheduler({publishPaperId : id.value}).then((res) => {
    if(res.code==200){
      paperDetailFn();
    }
  }).finally(e=>{
    loading.value = false;
  })
}

function sysNotifySubmitFn(){
  loading.value = true;
  sysNotifySubmit({publishPaperId : id.value}).then((res) => {
    if(res.code==200){
      createMessage.success(res.data);
    }
  }).finally(e=>{
    loading.value = false;
  })
}

</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}

.foot_item {
  display: flex;
  padding-top: 4px;
  padding-bottom: 2px;
  border-right: 1px solid #e8eaec;
  border-bottom: 1px solid #e8eaec;
  border-left: 1px solid #e8eaec;
  color: #606266;
}

.foot-c {
  justify-content: center;
  width: 100%;
}
.foot_item_row{
  width: 100%;
  text-align: center;
}
</style>
